<template>
  <view class="chat-container">
    <!-- <view class="chat-header">
      <text class="header-title">AI助手</text>
    </view> -->
    <view class="chat-history" ref="historyRef">
      <view
        v-for="(msg, index) in processedMessages"
        :key="index"
        class="message"
        :class="msg.role"
      >
        <view class="message-content">
          <template v-if="msg.type === 'text'">
            <text>{{ typeof msg.content === 'string' ? msg.content : '' }}</text>
          </template>
          <template v-else-if="msg.type === 'button_group'">
            <view class="button-group">
              <text class="button-group-text">{{ msg.content.text }}</text>
              <view class="button-grid">
                <button 
                  v-for="(btn, index) in msg.content.buttons" 
                  :key="index"
                  class="category-btn"
                  @click="handleCategoryClick(btn.value)"
                >
                  {{ btn.text }}
                </button>
              </view>
            </view>
          </template>
          <template v-else-if="msg.type === 'poi_list'">
            <view>
              <view class="ai-content">{{ msg.content.content }}</view>
              <view v-if="msg.content.poiMsg && msg.content.poiMsg.length > 0" class="poi-list">
                <view v-for="(poi, poiIndex) in msg.content.poiMsg" :key="poiIndex" class="poi-item">
                  <view class="poi-header">
                    <text class="poi-name">{{ poi.name }}</text>
                    <view class="poi-rating">
                      <text class="rating-text">评分: {{ poi.rating }}</text>
                      <view class="stars">
                        <text v-for="i in 5" :key="i" class="star" :class="{ filled: i <= Math.floor(poi.rating) }">★</text>
                      </view>
                    </view>
                  </view>
                  
                  <view v-if="poi._imageUrl" class="poi-image-container">
                    <image :src="poi._imageUrl" :alt="poi.name" class="poi-image" mode="aspectFill" />
                  </view>
                  
                  <view class="poi-details">
                    <view class="poi-location">
                      <text class="location-icon">📍</text>
                      <text>{{ poi.location }}</text>
                    </view>
                    <view class="poi-distance">
                      <text class="distance-icon">📏</text>
                      <text>{{ poi.distance }}米</text>
                    </view>
                    <view class="poi-distance">
                      <text class="distance-icon">🏡</text>
                      <text>{{ poi.address }}米</text>
                    </view>
                  </view>
                  
                  <view v-if="poi._distance > 700" class="taxi-container">
                    <TaxiButton :poi="poi" :distance="poi._distance"  />
                  </view>
                </view>
              </view>
            </view>
          </template>
        </view>
      </view>
      
      <view v-if="isThinking" class="message ai">
        <view class="message-content">
          <view class="thinking">
            <text>AI正在思考</text>
            <view class="dots">
              <view class="dot"></view>
              <view class="dot"></view>
              <view class="dot"></view>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <view class="input-container">
      <view class="input-wrapper">
        <textarea
          v-model="input"
          class="input-field"
          placeholder="请输入您的问题..."
          :disabled="isThinking"
        ></textarea>
        <button
          @click="sendMessage(false)"
          class="send-button"
          :disabled="!input.trim() || isThinking"
        >
          发送
        </button>
        <button
          @click="clearMessages"
          class="send-button"
          type="button"
        >
          清空
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, nextTick, computed } from 'vue'
import TaxiButton from '@/component/chatai/TaxiButton.vue'
import { getLocation } from '@/utils/getlocation'
import { onMounted } from 'vue'
// import axios from 'axios' // 移除 axios
import { useStore } from 'vuex'
const $store = useStore()
const city = $store.state.city
console.log(city)
const input = ref('')
const messages = ref([
  { 
    role: 'ai', 
    type: 'button_group', 
    content: {
      text: '请选择您需要的推荐类型：',
      buttons: [
        { text: '🍽️ 美食餐厅', value: '去餐厅' },
        { text: '🏨 酒店住宿', value: '去宾馆酒店' },
        { text: '🛍️ 咖啡奶茶', value: '去咖啡厅' },
        { text: '🎭 酒吧娱乐', value: '去酒吧' },
        { text: '🏥 医院诊所', value: '去综合医院' },
        { text: '🏞️ 景点公园', value: '我要去公园' }
      ]
    }
  }
])
const historyRef = ref(null)
const isLoading = ref(false)
const isThinking = ref(false) // 新增思考中状态

const sendMessage = async (isFromButton = false) => {
  if (!input.value.trim()) return
  messages.value.push({ role: 'user', type: 'text', content: input.value })
  const userInput = input.value
  input.value = ''
  
  // 显示思考中状态
  isThinking.value = true
  
  // 构建请求参数
  const requestData = {
    location: city.center,
    citycode: city.adcode,
    keywords: userInput,
    isKeywords: isFromButton // 按钮点击时为true，直接发送时为false
  }
  
  console.log('开始发送请求...')
  console.log('请求参数:', requestData)

  uni.request({
    // http://172.172.9.37:20025
    url: '/ai/getPOIMessage',
    method: 'POST',
    data: requestData,
    success: (res) => {
      console.log('请求成功，返回数据:', res)
      let aiType = 'text'
      let aiContent = res.data.data
      console.log('后端返回的 data:', aiContent)
      console.log('aiContent.poiMsg:', aiContent?.poiMsg)
      console.log('Array.isArray(aiContent.poiMsg):', Array.isArray(aiContent?.poiMsg))
      
      // 判断是否为带poiMsg的结构
      if (aiContent && aiContent.poiMsg && typeof aiContent.poiMsg === 'object') {
        aiType = 'poi_list'
      }
      
      console.log('设置的 type:', aiType)
      console.log('设置的 content:', aiContent)
      
      const newMessage = { role: 'ai', type: aiType, content: aiContent }
      console.log('准备添加的消息:', newMessage)
      
      messages.value.push(newMessage)
      console.log('当前所有消息:', messages.value)
      
      scrollToBottom()
    },
    fail: (err) => {
      console.log('请求失败:', err)
      messages.value.push({ role: 'ai', type: 'text', content: 'AI接口请求失败，请稍后再试。' })
      scrollToBottom()
    },
    complete: (res) => {
      console.log('请求完成:', res)
      // 清除思考中状态
      isThinking.value = false
    }
  })
}

const handleCategoryClick = (value) => {
  input.value = value
  sendMessage(true) // 标记来自按钮
}

const clearMessages = () => {
  // 先请求后端清空会话
  uni.request({
    url: '/ai/deleteMemary?phone=17640122174',
    method: 'Pgt', // 或 'GET'，根据后端接口实际要求
    success: (res) => {
      console.log('后端会话清空成功', res)
      // 清空前端消息，只保留第一条
      messages.value = [
        { 
          role: 'ai', 
          type: 'button_group', 
          content: {
            text: '请选择您需要的推荐类型：',
            buttons: [
            { text: '🍽️ 美食餐厅', value: '去餐厅' },
            { text: '🏨 酒店住宿', value: '去宾馆酒店' },
            { text: '🛍️ 咖啡奶茶', value: '去咖啡厅' },
            { text: '🎭 酒吧娱乐', value: '去酒吧' },
            { text: '🏥 医院诊所', value: '去综合医院' },
            { text: '🏞️ 景点公园', value: '我要去公园' }
            ]
          }
        }
      ]
    },
    fail: (err) => {
      console.error('后端会话清空失败', err)
      uni.showToast({
        title: '清空失败',
        icon: 'none'
      })
    }
  })
}

const scrollToBottom = () => {
  nextTick(() => {
    if (historyRef.value) {
      historyRef.value.scrollTop = historyRef.value.scrollHeight
    }
  })
}
onMounted(() => {
getLocation()
})
const getPoiImage = (poi) => {
  // 如果poi对象没有变化，直接返回缓存的结果
  if (poi._imageCache !== undefined) {
    return poi._imageCache;
  }
  
  let imageUrl = null;
  
  if (poi.image) {
    imageUrl = poi.image;
  } else if (poi.photos && poi.photos.length > 0) {
    imageUrl = poi.photos[0];
  } else if (poi.photo) {
    imageUrl = poi.photo;
  }
  
  // 缓存结果到poi对象上
  poi._imageCache = imageUrl;
  
  return imageUrl;
};

// 创建计算属性来处理POI图片，避免频繁重新计算
const processedMessages = computed(() => {
  return messages.value.map(msg => {
    if (msg.type === 'poi_list' && msg.content && msg.content.poiMsg) {
      return {
        ...msg,
        content: {
          ...msg.content,
          poiMsg: msg.content.poiMsg.map(poi => ({
            ...poi,
            _imageUrl: getPoiImage(poi),
            _distance: parseDistance(poi.distance)
          }))
        }
      };
    }
    return msg;
  });
});

// 解析距离字段，处理字符串和数字类型
const parseDistance = (distance) => {
  console.log('解析距离:', distance, typeof distance);
  if (typeof distance === 'number') {
    console.log('数字类型距离:', distance);
    return distance;
  }
  if (typeof distance === 'string') {
    // 移除"米"字并转换为数字
    const num = parseInt(distance.replace(/[^\d]/g, ''));
    console.log('字符串距离解析:', distance, '->', num);
    return isNaN(num) ? 0 : num;
  }
  console.log('无法解析的距离:', distance);
  return 0;
};
</script>

<style lang="scss" scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  max-width: 800px;
  width: 100%;
  height: 90vh;
  margin: 20px auto;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  position: relative;
  overflow: hidden;
  border-radius: 24px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="%23ffffff" opacity="0.1"/><circle cx="75" cy="75" r="1" fill="%23ffffff" opacity="0.1"/><circle cx="50" cy="10" r="0.5" fill="%23ffffff" opacity="0.1"/><circle cx="10" cy="60" r="0.5" fill="%23ffffff" opacity="0.1"/><circle cx="90" cy="40" r="0.5" fill="%23ffffff" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
    pointer-events: none;
    border-radius: 24px;
  }
  
  @media (max-width: 900px) {
    max-width: 95vw;
    height: 95vh;
    margin: 10px auto;
    border-radius: 20px;
  }
  
  @media (max-width: 700px) {
    max-width: 100vw;
    height: 100vh;
    margin: 0;
    border-radius: 0;
    
    &::before {
      border-radius: 0;
    }
  }
}

.chat-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  text-align: center;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
  position: relative;
  z-index: 10;
  
  h1 {
    margin: 0;
    font-size: 24px;
    font-weight: 700;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  
  @media (max-width: 700px) {
    padding: 16px;
    
    h1 {
      font-size: 20px;
    }
  }
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  scroll-behavior: smooth;
  position: relative;
  z-index: 5;
  max-height: calc(90vh - 140px); // 减去头部和输入框的高度
  
  @media (max-width: 900px) {
    max-height: calc(95vh - 140px);
    padding: 16px;
  }
  
  @media (max-width: 700px) {
    max-height: calc(100vh - 140px);
    padding: 16px;
  }
  
  &::-webkit-scrollbar {
    width: 6px;
  }
  
  &::-webkit-scrollbar-track {
    background: rgba(255, 255, 255, 0.1);
    border-radius: 3px;
  }
  
  &::-webkit-scrollbar-thumb {
    background: rgba(102, 126, 234, 0.3);
    border-radius: 3px;
    
    &:hover {
      background: rgba(102, 126, 234, 0.5);
    }
  }
}

.message {
  margin-bottom: 20px;
  display: flex;
  align-items: flex-start;
  gap: 12px;
  animation: fadeInUp 0.5s ease-out;
  
  @keyframes fadeInUp {
    from {
      opacity: 0;
      transform: translateY(20px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
  
  @media (max-width: 700px) {
    margin-bottom: 16px;
    gap: 8px;
  }
}

.message.user {
  flex-direction: row-reverse;
}

.message-content {
  max-width: 70%;
  padding: 16px 20px;
  border-radius: 24px;
  font-size: 16px;
  line-height: 1.6;
  word-break: break-word;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  position: relative;
  
  @media (max-width: 900px) {
    max-width: 75%;
    padding: 14px 16px;
    font-size: 15px;
  }
  
  @media (max-width: 700px) {
    max-width: 80%;
    padding: 14px 16px;
    font-size: 15px;
  }
}

.message.user .message-content {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-bottom-right-radius: 8px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.message.ai .message-content {
  background: white;
  color: #1e293b;
  border-bottom-left-radius: 8px;
  border: 1px solid rgba(102, 126, 234, 0.1);
}

.input-container {
  background: white;
  padding: 20px;
  border-top: 1px solid rgba(102, 126, 234, 0.1);
  box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 10;
  
  @media (max-width: 700px) {
    padding: 16px;
  }
}

.input-wrapper {
  display: flex;
  gap: 12px;
  align-items: flex-end;
  background: #f8fafc;
  border-radius: 24px;
  padding: 8px;
  border: 2px solid transparent;
  transition: all 0.3s ease;
  
  &:focus-within {
    border-color: #667eea;
    background: white;
    box-shadow: 0 4px 20px rgba(102, 126, 234, 0.15);
  }
  
  @media (max-width: 700px) {
    gap: 8px;
    padding: 6px;
  }
}

.input-field {
  flex: 1;
  border: none;
  outline: none;
  background: transparent;
  font-size: 16px;
  line-height: 1.5;
  color: #1e293b;
  resize: none;
  min-height: 24px;
  max-height: 120px;
  padding: 8px 0;
  
  &::placeholder {
    color: #94a3b8;
  }
  
  @media (max-width: 700px) {
    font-size: 15px;
  }
}

.send-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 20px;
  padding: 12px 20px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
    transition: left 0.5s;
  }
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
    
    &::before {
      left: 100%;
    }
  }
  
  &:active {
    transform: translateY(0);
  }
  
  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none;
  }
  
  @media (max-width: 700px) {
    padding: 10px 16px;
    font-size: 14px;
    border-radius: 18px;
  }
}
.poi-item {
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 2px solid #e2e8f0;
  &:last-child {
    border-bottom: none;
  }
}
.poi-photo {
  width: 100%;
  max-width: 150px;
  height: auto;
  border-radius: 8px;
  display: block;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.button-group {
  padding: 20px;
  border-radius: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
  margin-bottom: 8px;
  @media (max-width: 700px) {
    padding: 16px;
    border-radius: 20px;
  }
}

.button-group-text {
  font-size: 18px;
  line-height: 1.6;
  word-break: break-all;
  margin-bottom: 20px;
  color: white;
  font-weight: 600;
  text-align: center;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  @media (max-width: 700px) {
    font-size: 16px;
    margin-bottom: 16px;
  }
}

.button-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 10px;
  
  @media (max-width: 900px) {
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }
  
  @media (max-width: 700px) {
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }
}

.category-btn {
  padding: 14px 16px;
  border-radius: 16px;
  border: none;
  background: rgba(255, 255, 255, 0.95);
  color: #4a5568;
  font-size: 14px;
  font-weight: 600;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
    transition: left 0.5s;
  }
  
  &:hover {
    background: rgba(255, 255, 255, 1);
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
    
    &::before {
      left: 100%;
    }
  }
  
  &:active {
    transform: translateY(0);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  }
  
  @media (max-width: 700px) {
    padding: 12px 14px;
    font-size: 13px;
    border-radius: 14px;
  }
}

.ai-content {
  font-size: 16px;
  line-height: 1.6;
  color: #1e293b;
  margin-bottom: 16px;
  padding: 12px 16px;
  background: rgba(102, 126, 234, 0.05);
  border-radius: 12px;
  border-left: 4px solid #667eea;
  
  @media (max-width: 700px) {
    font-size: 15px;
    padding: 10px 12px;
  }
}

.poi-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.poi-item {
  background: white;
  border-radius: 16px;
  padding: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(102, 126, 234, 0.1);
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  }
  
  @media (max-width: 900px) {
    padding: 14px;
    border-radius: 14px;
  }
  
  @media (max-width: 700px) {
    padding: 12px;
    border-radius: 12px;
  }
}

.poi-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  gap: 12px;
  
  @media (max-width: 700px) {
    flex-direction: column;
    gap: 8px;
  }
}

.poi-name {
  font-size: 18px;
  font-weight: 700;
  color: #1e293b;
  margin: 0;
  line-height: 1.4;
  
  @media (max-width: 700px) {
    font-size: 16px;
  }
}

.poi-rating {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
  
  @media (max-width: 700px) {
    align-items: flex-start;
  }
}

.rating-text {
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
}

.stars {
  display: flex;
  gap: 2px;
}

.star {
  font-size: 16px;
  color: #e2e8f0;
  
  &.filled {
    color: #fbbf24;
  }
}

.poi-image-container {
  margin: 16px 0;
  position: relative;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.poi-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  display: block;
  
  @media (max-width: 700px) {
    height: 160px;
  }
}

.poi-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin: 16px 0;
}

.poi-location,
.poi-distance {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #64748b;
  
  .location-icon,
  .distance-icon {
    font-size: 16px;
  }
}

.taxi-container {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid rgba(102, 126, 234, 0.1);
}

.taxi-btn-below-image {
  margin-top: 12px;
}

.thinking {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  color: #64748b;
  
  .dots {
    display: flex;
    gap: 4px;
  }
  
  .dot {
    width: 6px;
    height: 6px;
    background: #667eea;
    border-radius: 50%;
    animation: thinking 1.4s infinite ease-in-out;
    
    &:nth-child(1) { animation-delay: -0.32s; }
    &:nth-child(2) { animation-delay: -0.16s; }
    &:nth-child(3) { animation-delay: 0s; }
  }
  
  @keyframes thinking {
    0%, 80%, 100% {
      transform: scale(0.8);
      opacity: 0.5;
    }
    40% {
      transform: scale(1);
      opacity: 1;
    }
  }
}
.clear-btn-container {
  text-align: right;
  margin: 10px 20px 0 0;
}
.clear-btn {
  background: #f87171;
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 4px 10px;
  font-size: 12px;
  cursor: pointer;
  line-height: 1;
  height: 32px;
  margin-left: 6px;
  min-width: 0;
  transition: background 0.2s;
}
.clear-btn:hover {
  background: #dc2626;
}
</style>